package com.xiaouyudeguang.common.handler;

import com.xiaouyudeguang.common.collect.MapBuilder;
import com.xiaouyudeguang.common.constants.Headers;
import com.xiaouyudeguang.common.dicode.service.DiCodeService;
import com.xiaouyudeguang.common.dirule.entity.DiRule;
import com.xiaouyudeguang.common.dirule.service.DiRuleService;
import com.xiaouyudeguang.common.utils.DroolsUtils;
import com.xiaouyudeguang.common.request.RequestDto;
import com.xiaouyudeguang.common.respose.ResultDto;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@Slf4j
public class DroolsHttpRequestHandler implements DefaultHttpRequestHandler {

    @Autowired
    private DiCodeService diCodeService;

    @Autowired
    private DiRuleService diRuleService;

    @Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        String parameters = RequestUtils.getParameters(request);
        String requestURI = request.getRequestURI();
        String[] pathVariables = requestURI.split("/");
        try {
            ResultDto<Object> resultDto = new ResultDto<>();
            String tenantId = request.getHeader(Headers.TENANT_ID);
            String appId = request.getHeader(Headers.APP_ID);
            Map<String, String> props = MapBuilder.of();
            props.put("tenantId", tenantId);
            props.put("appId", appId);
            props.put("tableName", pathVariables[1]);
            props.put("methodName", pathVariables[2]);
            if (pathVariables.length == 4) {
                props.put("id", pathVariables[3]);
            }
            DiRule diRule = diRuleService.getRule(tenantId, appId, "2", pathVariables[1], pathVariables[2]);
            KieSession kieSession = diRule == null ? DroolsUtils.newKieSession(props) : DroolsUtils.newKieSession(diRule.getContent(), diRule.getName(), props);
            kieSession.insert(JsonObject.fromJson(parameters, RequestDto.class));
            kieSession.setGlobal("log", log);
            kieSession.setGlobal("service", diCodeService);
            kieSession.insert(resultDto);
            kieSession.fireAllRules();
            response.getWriter().print(resultDto);
        } catch (Exception e) {
            response.getWriter().print(ResultDto.err(e.getMessage()));
        }
    }
}

